#include "wavapi.h"
#include <SDL/SDL.h>
//#pragma comment(lib,"SDL.lib")
//#pragma comment(lib,"SDLmain.lib")
//音频回调函数，userdata 用户数据 ，stream 音频缓冲指针 ，len可输入缓冲长度
static void my_audio_callback(void *userdata, Uint8 *stream, int len);
//自己建了个结构体存储音频相关信息
/*
typedef struct _WavBuffer{
char *wav_buffer;
int wav_length;
int wav_lastlength;
char *wav_pos;
}WavBuffer;*/
int PlayWavBySDL(const char*filename){
	SDL_AudioSpec wav_spec={0};
	WavBuffer wav_info={0};
	int times=0;
//打开WAV文件，wav_spec保持音频格式，wav_buffer会一次性读取音频数据，wav_length音频数据长度
	if(SDL_LoadWAV(filename,&wav_spec,&wav_info.wav_buffer,&wav_info.wav_length)==NULL){
	   printf("read err\n");
	}
	wav_info.wav_pos=wav_info.wav_buffer;
	wav_info.wav_lastlength=wav_info.wav_length;
	wav_spec.callback=my_audio_callback;
	wav_spec.userdata=&wav_info;
//打开音频设备
	if(SDL_OpenAudio(&wav_spec,NULL)<0){
		printf("OpenAudio Error\n");
		SDL_FreeWAV(wav_info.wav_buffer);
		return 0;
	}
	printf("StartPlay By SDL\n");
	SDL_PauseAudio(0);
//如果还有数据没写入就等待
	while(wav_info.wav_lastlength>0){
		int timestamp=(wav_info.wav_pos-wav_info.wav_buffer)*100/(wav_spec.freq*wav_spec.channels*(wav_spec.format&0xFF)/8);
		printf("\rTime %02d:%02d.%02d min",times/6000,times/100%60,times%100);
		SDL_Delay(100);
		times+=100;
	}
	printf("\nStopPlay\n");
	SDL_CloseAudio();
//释放音频数据
	SDL_FreeWAV(wav_info.wav_buffer);
	return 0;
}
void my_audio_callback(void *userdata, Uint8 *stream, int len){
	WavBuffer*wavinfo=(WavBuffer*)userdata;
	len=(len<wavinfo->wav_lastlength)?len:wavinfo->wav_lastlength;
//写入音频数据
	SDL_MixAudio(stream,wavinfo->wav_pos,len,SDL_MIX_MAXVOLUME);
	wavinfo->wav_lastlength-=len;
	wavinfo->wav_pos+=len;
}